<?php
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username == '' or $password == '') {
    echo "<script>alert('用户名和密码都必须要填写！');history.back();</script>";
    exit;
}
$sex = $_POST['sex'];
$email = trim($_POST['email']);
$age = $_POST['age'];
$fav = @$_POST['fav'];
$ren = $_POST['ren'];
include_once "conn.php";
if ($_FILES["pic"]["error"] !== 0 && $_FILES["pic"]["error"] !== 4) {  //头像上传失败
    echo "<script>alert('头像上传错误！');history.back();</script>";
} else if ($_FILES["pic"]["error"] !== 4) {
    $allowedExts = array("jpg", "gif", "jpeg", "png");  // 允许上传的图片后缀
    $temp = explode(".", $_FILES["pic"]["name"]);   //得到一个数组
    $extension = end($temp);    // 获取文件后缀名
    if ((($_FILES["pic"]["type"] === "image/gif")
            || ($_FILES["pic"]["type"] == "image/jpeg")
            || ($_FILES["pic"]["type"] == "image/jpg")
            || ($_FILES["pic"]["type"] == "image/png")
        )
        && ($_FILES["pic"]["size"] < 204800)   // 小于 200 kb
        && in_array/*数组中是否存在指定的值*/
        ($extension, $allowedExts)) {
        $move = iconv("utf-8", "gb2312//IGNORE", $username);
        if (move_uploaded_file($_FILES["pic"]["tmp_name"]/*上传文件*/, "upload/" . $move . "." . $extension)) {
            $sql = "insert into userinfo (username,pw,sex,age,email,fav,pic,ren) VALUE ('$username','" . md5($password) . "','$sex','" . $age . "','$email','" . implode(",", $fav) . "','" . $username . "." . $extension . "','$ren')";
            $result = mysqli_query($conn, $sql);
            $num = mysqli_affected_rows($conn); //返回上一次数据库操作受影响的行数
            if ($num) {
                echo "<script>alert('恭喜你，注册成功！');location.href='index.php';</script>";
            } else {
                echo "<script>alert(\"注册失败！原因为：" . mysqli_error($conn) . "\");history.back();</script>";
            }
        } else {
            echo "<script>alert('头像上传错误');history.back();</script>";
            exit;
        }
    } else {
        echo "<script>alert('头像格式错误，仅支持JPG，JPEG,PNG,GIF格式。');history.back();</script>";
        exit;
    }
} else {
    $sql = "insert into userinfo (username,pw,sex,age,email,fav,ren) VALUE ('$username','" . md5($password) . "','$sex','" . $age . "','$email','" . implode(",", $fav) . "','$ren')";
    $result = mysqli_query($conn, $sql);
    $num = mysqli_affected_rows($conn); //返回上一次数据库操作受影响的行数
    if ($num) {
        echo "<script>alert('恭喜你，注册成功！');location.href='index.php#tologin';</script>";
    } else {
        echo "<script>alert(\"注册失败！原因为：" . mysqli_error($conn) . "\");history.back();</script>";
    }
}
mysqli_close($conn);
?>